import { createHash } from 'crypto';
import * as path from 'path';
import { promises as fs } from 'fs';
import { tempDir, readfile } from './utils';

export interface IPid {
  id: string;
  pid: number;
}

/**
 * 获取 .pid 文件路径
 */
export async function pidFilepath(): Promise<string> {
  return path.join(await tempDir(), '.pid');
}

/**
 * 读取 .pid 文件
 */
export async function readPid(): Promise<IPid[]> {
  const pidFile = await pidFilepath();
  const content = await readfile(pidFile);
  return content ? JSON.parse(content) : [];
}

/**
 * 写入 .pid 文件
 */
export async function writePid(data: IPid[]): Promise<void> {
  await fs.writeFile(await pidFilepath(), JSON.stringify(data, null, 2), 'utf-8');
}

/**
 * 启动时检查id 并写入 .pid 文件
 */
export async function startAndWritePid(data: IPid): Promise<void> {
  const id = data.id = data.id || createHash('md5').update(new Date().toString()).digest('hex').slice(0, 6);
  const list = await readPid();
  if (list.some(item => item.id === id)) {
    console.error(`${id} 已存在，请更换 id 或停止运行${id}（tagup stop ${id}）`);
    process.exit();
  } else {
    list.push(data);
    await writePid(list);
  }
}
